﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using TPOJ.Model;
using TPOJ.Core;
using System.IO;

namespace TPOJ.BLL
{
    public static class JudgeBOSynchronous
    {
        public static void Judge(int problemId, string language, string code, int userId, string sourcePath, string testsPath, string outputPath, int? contestId, DateTime submitTime)
        {
            SolutionBO solutionBO = new SolutionBO();
            Solution solution = solutionBO.AddSolution(problemId, language, code, userId, contestId, submitTime);

            if (contestId != null)
            {
                int cellId = Utils.GetContestProblemLabel(contestId.Value, problemId);
                Utils.UpdateStanding(contestId.Value, userId, cellId, submitTime, ResultType.Pending, 1);
            }

            sourcePath += solution.UniqueID + ".code";

            Environment.SetEnvironmentVariable("path", Environment.GetEnvironmentVariable("path") + @";C:\Users\lehope\Documents\Visual Studio 2010\Projects\TPOJ\TPOJ.Web\Config\C#\;");

            MakeTempFile(solution.Code, sourcePath);

            Language lang = new Language(solution.Language, @"C:\Users\lehope\Documents\Visual Studio 2010\Projects\TPOJ\TPOJ.Web\Config\Compilers.config");
            Engine engine = new Engine(sourcePath, outputPath, testsPath, lang, solution.Problem.TimeLimit, solution.Problem.MemoryLimit);
            Result r = engine.Judge();

            solution.Result = (byte)r.ResultType;
            solution.ErrorMessage = r.ErrorMessage;
            solution.Time = Convert.ToInt32(r.Time);
            solution.Memory = Convert.ToInt32(r.Memory);
            bool isAC = r.ResultType == ResultType.Accepted;
            solutionBO.EditSolution(solution, isAC);
            if (contestId != null)
            {
                int cellId = Utils.GetContestProblemLabel(contestId.Value, problemId);
                Utils.UpdateStanding(contestId.Value, userId, cellId, submitTime,r.ResultType, 0);
            }
        }

        private static void MakeTempFile(string code,string path)
        {
            using (var file = File.CreateText(path))
            {
                file.Write(code);
            }
        }
    }
}
